/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useEffect, useRef, useState } from 'react';
import { DrawerForm, ProFormSelect, ProFormText } from '@ant-design/pro-form';
import { message, Button } from 'antd';
import type { ConnectState } from '@/models/connect';
import type { ProFormInstance } from '@ant-design/pro-form';
import {
  getDeliveryAccountList,
  addCustomers,
  getCustomersInfo,
  getAccountCityList,
} from '@/services/jdk/customers';
import { delivery_brand_options } from '@/components/_pages/jdk/customers/_utils';
import { useSelector } from 'umi';

type PropsType = {
  actionRef: any;
  visible: boolean;
  record: any;
  onClose: () => void;
};

type formValues = {
  brand: string;
  auth_id: string;
  account_level: string;
  address: string[];
  account: string;
  city: string;
};

const Index: React.FC<PropsType> = (props) => {
  const { visible, record = {}, onClose, actionRef } = props;
  const [loading, setLoading] = useState<boolean>(false);
  const formRef = useRef<ProFormInstance>();
  const [customers, setCustomers] = useState<{ label: string; value: string }[]>([]);
  const { winSize } = useSelector((state: ConnectState) => state.global);
  const accountRef = useRef<any>({ canVal: true });
  const [val, setVal] = useState<any>();
  const [open, setOpen] = useState<boolean>(false);

  const handleSubmit = async (values: formValues) => {
    const { user_id = '' } = record || {};
    const reqData = {
      ...values,
      user_id,
    };
    const { code, msg } = await addCustomers(reqData);
    if (code == 0) {
      onClose();
      message.success(msg);
      actionRef.current?.reload();
    } else {
      message.error(msg);
    }
  };

  const removeData = () => {
    setCustomers([]);
  };

  const handleSearch = async () => {
    formRef.current?.validateFields(['account']).then(async (res) => {
      const { account = '' } = res;
      if (account) {
        setLoading(true);
        const { code, data, msg } = await getCustomersInfo({ account });
        if (code == 0) {
          const customersInfo = {
            phone: '手机号',
            nickname: '商家名称',
            address: '商家地址',
          };
          const customersData = Object.keys(customersInfo).map((item) => ({
            label: customersInfo[item],
            value: data[item],
          }));
          setCustomers(customersData);
        } else {
          removeData();
          message.error(msg);
        }
        setLoading(false);
      }
    });
  };

  const handleClose = () => {
    onClose();
  };

  useEffect(() => {
    return () => {
      setCustomers([]);
      formRef.current?.resetFields();
    };
  }, []);

  return (
    <DrawerForm
      title='添加/修改大客户'
      formRef={formRef}
      width={winSize === 'xs' ? '80%' : 500}
      visible={visible}
      labelAlign='left'
      layout='horizontal'
      labelCol={{
        span: 5,
      }}
      drawerProps={{
        onClose: handleClose,
        destroyOnClose: true,
      }}
      onFinish={(values: formValues) => handleSubmit(values)}
      initialValues={{
        brand: 'gxd',
        account: record.phone,
        city: '遂宁市',
        ...(record || {}),
      }}
    >
      <ProFormSelect
        name='brand'
        label='运力品牌'
        disabled={!!record.user_id}
        placeholder='请选择运力品牌'
        fieldProps={{
          allowClear: false,
        }}
        valueEnum={delivery_brand_options}
        rules={[{ required: true, message: '请选择运力品牌' }]}
      />
      <ProFormSelect
        name='city'
        label='所在城市'
        showSearch
        fieldProps={{
          placeholder: '请选择城市',
        }}
        valueEnum={{
          gxd: '遂宁市',
        }}
        request={getAccountCityList}
        rules={[{ required: true, message: '请选择城市' }]}
      />
      <ProFormSelect
        name='auth_id'
        label='运力账号'
        showSearch
        dependencies={['city']}
        fieldProps={{
          placeholder: '请输入/选择运力账号',
          allowClear: false,
          showArrow: false,
          searchValue: val,
          open: open,
          onSearch: (value: string) => {
            if (accountRef.current.canVal) {
              setVal(value);
              formRef.current?.setFieldsValue({ auth_id: value });
            }
            accountRef.current.canVal = true;
          },
          onFocus: () => {
            setOpen(true);
            accountRef.current.canVal = true;
          },
          onBlur: () => {
            if (val) {
              accountRef.current.canVal = false;
            }
            setOpen(false);
          },
          onSelect: (value: string) => {
            accountRef.current.canVal = false;
            formRef.current?.setFieldsValue({ auth_id: value });
            setOpen(false);
          },
        }}
        request={() => {
          const city = formRef.current?.getFieldsValue(['city']) || {
            city: record.city || '遂宁市',
          };
          return getDeliveryAccountList(city);
        }}
        rules={[{ required: true, message: '请输入/选择运力账号' }]}
      />
      <ProFormText
        name='account'
        label='商家账号'
        placeholder='输入账号'
        disabled={!!record.user_id}
        rules={[
          { required: true, message: '请输入商家账号' },
          { pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: '请输入正确手机号' },
        ]}
        addonAfter={
          !record.user_id ? (
            <Button onClick={handleSearch} loading={loading}>
              查询
            </Button>
          ) : null
        }
      />
      {customers.length > 0 ? (
        <div>
          {customers.map((item) => {
            return (
              <ProFormText
                readonly
                key={item.label}
                label={item.label}
                fieldProps={{
                  value: item.value,
                }}
              />
            );
          })}
        </div>
      ) : null}
    </DrawerForm>
  );
};

export default Index;
